package com.example.administrator.printoutindemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.printoutindemo.services.Tools;
import com.example.administrator.printoutindemo.view.MyImageButton;
import com.example.administrator.printoutindemo.zxing.activity.CaptureActivity;


import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.List;


public class ListByQRCodeActivity extends Activity {
	private MyImageButton store_btn_QRCode = null;
	private TextView s_qrc_projectname = null;
	private TextView s_qrc_material = null;
	private TextView s_qrc_contractdate = null;
	private TextView s_qrc_supplydate = null;
	private TextView s_qrc_lastinstoredate = null;
	private TextView s_qrc_num = null;
	private TextView s_qrc_nums = null;
	private TextView s_qrc_slink = null;
	private TextView s_qrc_sphone = null;
	private TextView s_qrc_remark = null;
	private TextView s_qrc_sname = null;
	private TextView s_qrc_mnums = null;

	private TextView s_qrc_rsstatus = null;
	private TextView s_qrc_recoveryOrScrapTime = null;
	private TextView s_qrc_rsnums= null;
	private TextView s_qrc_rsprojectname = null;
	private TextView s_qrc_rsaddress = null;

	private ListView store_listView = null;
	private StoreListOutStorageAdapter storeListOutStorageAdapter = null;

	String scanResult = "";
	ProgressDialog progressDiaog;
	StoreListOutStorageAdapter adapter = null;

	List<InfoByQRCodeMid> list_InfoByQRCodeMid = null;
	List<Outstorage> list_outStorage = null;

	private InfoByQRCodeMid infoByQRCodeMid = null;
	private Outstorage outStorage = null;

	private static final String WEBSERVICE_CONFIG = "webServiceInfo";

	private static final int STOP = 0;
	private static final int THREADING = 1;

	Handler hanlder = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case STOP:

					if (list_InfoByQRCodeMid.size() == 1) {
						InfoByQRCodeMid in = list_InfoByQRCodeMid.get(0);

						String projectname = Tools.ToDBC(Tools.stringFilter(in
								.get_projectname()));
						String material = Tools.ToDBC(Tools.stringFilter(in
								.get_material()));
						String contractdate = Tools.ToDBC(Tools.stringFilter(in
								.get_contractdate()));
						String supplydate = Tools.ToDBC(Tools.stringFilter(in
								.get_supplydate()));
						String lastinstoredate = Tools.ToDBC(Tools.stringFilter(in
								.get_lastinstoredate()));
						String num = Tools.ToDBC(Tools.stringFilter(in.get_num()))
								+ Tools.ToDBC(Tools.stringFilter(in.get_unit()));
						String nums = Tools
								.ToDBC(Tools.stringFilter(in.get_nums()))
								+ Tools.ToDBC(Tools.stringFilter(in.get_unit()));
						String mnums = Tools
								.ToDBC(Tools.stringFilter(in.get_mnums()))
								+ Tools.ToDBC(Tools.stringFilter(in.get_unit()));
						String sname = Tools.ToDBC(Tools.stringFilter(in
								.get_sname()));
						String slink = Tools.ToDBC(Tools.stringFilter(in
								.get_slink()));
						String sphone = Tools.ToDBC(Tools.stringFilter(in
								.get_sphone()));
						String remark = Tools.ToDBC(Tools.stringFilter(in.get_remark()));
						String rstime = Tools.ToDBC(Tools.stringFilter(in.get_recoveryOrScrapTime()));
						String rsnums = Tools.ToDBC(Tools.stringFilter(in.get_rsnums()));
						String rsstatus = Tools.ToDBC(Tools.stringFilter(in.get_status()));
						String rsprojectname = Tools.ToDBC(Tools.stringFilter(in.get_rsprojectname()));
						String rsaddress = Tools.ToDBC(Tools.stringFilter(in.get_arrivalAddress()));

						s_qrc_projectname.setText(projectname);
						s_qrc_material.setText(material);
						if(!contractdate.equals("null"))
							s_qrc_contractdate.setText(contractdate);
						s_qrc_supplydate.setText(supplydate);
						s_qrc_lastinstoredate.setText(lastinstoredate);
						s_qrc_num.setText(num);
						s_qrc_nums.setText(nums);
						s_qrc_mnums.setText(mnums);
						s_qrc_sname.setText(sname);
						s_qrc_slink.setText(slink);
						s_qrc_sphone.setText(sphone);
						s_qrc_remark.setText(remark);

						if (rsstatus.equals("2")) {
							s_qrc_rsstatus.setText("报废");
						}else if (rsstatus.equals("3")) {
							s_qrc_rsstatus.setText("回收");
						}else {
							s_qrc_rsstatus.setText("");
						}

						if(!rstime.equals("null"))
							s_qrc_recoveryOrScrapTime.setText(rstime);
						if(!rsnums.equals("null"))
							s_qrc_rsnums.setText(rsnums);
						if(!rsprojectname.equals("null"))
							s_qrc_rsprojectname.setText(rsprojectname);
						if(!rsaddress.equals("null"))
							s_qrc_rsaddress.setText(rsaddress);

						// s_qrc_material.setText("Android提供了精巧和有力的组件化模型构建用户的UI部分。主要是基于布局类："
						// +
						// "View和        ViewGroup。在此基础上，android平台提供了大量的预制的View和xxxViewGroup子类，"
						// + "即布局（layout）和窗口小部件（widget）。可以用它们构建自己的UI。");

						adapter.setList(list_outStorage);
						store_listView.setAdapter(adapter);

					}

					progressDiaog.dismiss();
					break;

				case THREADING:

					progressDiaog.dismiss();
					break;

			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.store_activity_listqrcode);

		store_btn_QRCode = (MyImageButton) findViewById(R.id.store_btn_QRCode);
		s_qrc_projectname = (TextView) findViewById(R.id.s_qrc_projectname);
		s_qrc_material = (TextView) findViewById(R.id.s_qrc_material);
		s_qrc_contractdate = (TextView) findViewById(R.id.s_qrc_contractdate);
		s_qrc_supplydate = (TextView) findViewById(R.id.s_qrc_supplydate);
		s_qrc_lastinstoredate = (TextView) findViewById(R.id.s_qrc_lastinstoredate);
		s_qrc_num = (TextView) findViewById(R.id.s_qrc_num);
		s_qrc_nums = (TextView) findViewById(R.id.s_qrc_nums);
		s_qrc_sphone = (TextView) findViewById(R.id.s_qrc_sphone);
		s_qrc_slink = (TextView) findViewById(R.id.s_qrc_slink);
		s_qrc_remark = (TextView) findViewById(R.id.s_qrc_remark);
		s_qrc_rsstatus = (TextView) findViewById(R.id.s_qrc_rsstatus);
		s_qrc_recoveryOrScrapTime = (TextView) findViewById(R.id.s_qrc_recoveryOrScrapTime);
		s_qrc_rsnums = (TextView) findViewById(R.id.s_qrc_rsnums);
		s_qrc_rsprojectname = (TextView) findViewById(R.id.s_qrc_rsprojectname);
		s_qrc_rsaddress = (TextView) findViewById(R.id.s_qrc_rsaddress);
		s_qrc_sname = (TextView) findViewById(R.id.s_qrc_sname);
		s_qrc_mnums = (TextView) findViewById(R.id.s_qrc_mnums);

		store_listView = (ListView) findViewById(R.id.store_listView);

		infoByQRCodeMid = new InfoByQRCodeMid(this);
		outStorage = new Outstorage(this);

		adapter = new StoreListOutStorageAdapter(this);

		store_btn_QRCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent openCameraIntent = new Intent(ListByQRCodeActivity.this,
						CaptureActivity.class);
				startActivityForResult(openCameraIntent, 0);
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			scanResult = bundle.getString("result");
			// lbl_QRCode.setText(scanResult);

			progressDiaog = new ProgressDialog(ListByQRCodeActivity.this);
			progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
			progressDiaog.setTitle("提示");
			// progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
			progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
			progressDiaog.setIndeterminate(false);// 设置进度条不明确
			progressDiaog.setCancelable(true);

			progressDiaog.show();

			new Thread() {
				@Override
				public void run() {



					list_InfoByQRCodeMid = GetListInfoByQRCodeMidFromWebService(scanResult);
					list_outStorage = GetOutstorageFromWebService(scanResult);

					if (list_InfoByQRCodeMid.size() == 1) {
						Message m = new Message();
						m.what = ListByQRCodeActivity.STOP;
						hanlder.sendMessage(m);
					}
				}
			}.start();

		}
	}

	// 获取出库记录信息
	private List<Outstorage> GetOutstorageFromWebService(
			String mid) {

		List<Outstorage> list = null;
		try {
			/****************** 调用webService ***********************/
			// 调用.net 的WebService.
			String nameSpace = "http://dyjapp.org/";
			String methodName = "GetListOutStorageByQRCodeMid";

			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			String url = "http://" + sPreferencces.getString("ip", "") + ":"
					+ sPreferencces.getString("Port", "")
					+ "/StoreService.asmx";
			String soapAction = nameSpace + methodName;

			// 设置连接参数
			SoapObject request = new SoapObject(nameSpace, methodName);

			// 增加属性参数。 将相关的函数参数放入到过程中。
			request.addProperty("mid", mid);
			// request.addProperty("pass", edtPwd.getText().toString());
			// request.addProperty("sYardCode", "WLY");

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
			// V1.1）;

			// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
			// 不指定rpc方式则用true否则要用false
			envelope.dotNet = true;

			// envelope.setOutputSoapObject(request);//设置请求参数
			envelope.bodyOut = request; // enveloper.bodyOut=request 与
			// envelope.setOutputSoapObject(request)
			// 效果相同。
			// step4 创建HttpTransportSE对象
			HttpTransportSE ht = new HttpTransportSE(url);
			// step5 调用WebService
			ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
			if (envelope.getResponse() != null) {
				SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

				String returnStr = response.toString();

				if ("" != returnStr) {
					returnStr = returnStr.substring(returnStr.lastIndexOf("["),
							returnStr.length());

					returnStr = returnStr.replace("\\", "");

					list = outStorage.getListFromJSON(returnStr);

				}

			}
			/****************** 调用webService结束 ***********************/

		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}

	// 获取基本信息
	private List<InfoByQRCodeMid> GetListInfoByQRCodeMidFromWebService(
			String mid) {

		List<InfoByQRCodeMid> list = null;
		try {
			/****************** 调用webService ***********************/
			// 调用.net 的WebService.
			String nameSpace = "http://dyjapp.org/";
			String methodName = "GetInfoByQRCodeMid";

			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			String url = "http://" + sPreferencces.getString("ip", "") + ":"
					+ sPreferencces.getString("Port", "")
					+ "/StoreService.asmx";
			String soapAction = nameSpace + methodName;

			// 设置连接参数
			SoapObject request = new SoapObject(nameSpace, methodName);

			// 增加属性参数。 将相关的函数参数放入到过程中。
			request.addProperty("mid", mid);
			// request.addProperty("pass", edtPwd.getText().toString());
			// request.addProperty("sYardCode", "WLY");

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
			// V1.1）;

			// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
			// 不指定rpc方式则用true否则要用false
			envelope.dotNet = true;

			// envelope.setOutputSoapObject(request);//设置请求参数
			envelope.bodyOut = request; // enveloper.bodyOut=request 与
			// envelope.setOutputSoapObject(request)
			// 效果相同。
			// step4 创建HttpTransportSE对象
			HttpTransportSE ht = new HttpTransportSE(url);
			// step5 调用WebService
			ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
			if (envelope.getResponse() != null) {
				SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

				String returnStr = response.toString();

				if ("" != returnStr) {
					returnStr = returnStr.substring(returnStr.lastIndexOf("["),
							returnStr.length());

					returnStr = returnStr.replace("\\", "");

					list = infoByQRCodeMid.getListFromJSON(returnStr);

				}

			}
			/****************** 调用webService结束 ***********************/

		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}

	// // 扫描二维码事件
	// private class store_btn_QRCodeClick implements OnClickListener {
	// @Override
	// public void onClick(View v) {
	// // TODO Auto-generated method stub
	// Intent intent = new Intent();
	// intent.setClass(ModifyPageActivity.this, ListFarmActivity.class);
	// startActivity(intent);
	// }
	// }

}